package com.dao;

import com.bean.Account;
import com.utils.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountDao {
    /**
     * 登录方法
     * @param username
     * @param password
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public Account login(String username, String password) throws SQLException, ClassNotFoundException {
        String sql = "select id, username, password, gender, email from account where username = ? and password = ?";
        System.out.println("要执行的语句是：" + sql);

        try (Connection connection = DBHelper.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)){
            statement.setString(1, username);
            statement.setString(2, password);

            try(ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    Account account = new Account();
                    account.setId(resultSet.getInt(1));
                    account.setUsername(resultSet.getString(2));
                    account.setPassword(resultSet.getString(3));
                    account.setGender(resultSet.getString(4));
                    account.setEmail(resultSet.getString(5));
                    return account;
                } else {
                    return null;
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        System.out.println(new AccountDao().login("曾小明", "080500"));
        System.out.println("登录成功！");
    }

    /**
     * 注册方法
     * @param account
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public void register(Account account) throws SQLException, ClassNotFoundException {
        String sql = "insert into account (username, password, gender, email) values (?, ?, ?, ?)";
        System.out.println("要执行的语句是：" + sql);

        try (Connection connection = DBHelper.getConnection();
            PreparedStatement statement = connection.prepareStatement(sql)){
            statement.setString(1, account.getUsername());
            statement.setString(2, account.getPassword());
            statement.setString(3, account.getGender());
            statement.setString(4, account.getEmail());
            statement.executeUpdate();
        }
    }
}
